package com.lx.input.flatFile;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * @author lixing
 * @date 2021/7/12 19:32
 */
@Configuration
public class InputFaltFileItemReaderConfigruation {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    @Qualifier("flatFileWriterDemo")
    private ItemWriter<? super AlipayTranDo> FlatFileWriterDemo;

    @Bean
    public Job FaltFileItemReaderJob() {
        return jobBuilderFactory.get("flatFileItemReader")
                .start(FaltFileItemReaderJobStep())
                .build();
    }

    @Bean
    public Step FaltFileItemReaderJobStep() {
        return stepBuilderFactory.get("FaltFileItemReaderJobStep")
                .<AlipayTranDo, AlipayTranDo>chunk(3)
                .reader(FaltFileReaderDemo())
                .writer(FlatFileWriterDemo)
                .build();
    }

    @Bean
    @StepScope
    public FlatFileItemReader<AlipayTranDo> FaltFileReaderDemo() {
        FlatFileItemReader<AlipayTranDo> reader=new FlatFileItemReader<AlipayTranDo>();
//        reader.setResource(new ClassPathResource("/customer.csv"));


        Resource resource = new ClassPathResource("customer.csv");
        reader.setResource(resource);

        reader.setLinesToSkip(1);//跳过前1行

        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); //解析器
        tokenizer.setNames(new String[]
                {"tranId","channel","tranType","counterparty","goods","amount","isDebitCredit","state"}
        );
        DefaultLineMapper<AlipayTranDo> lineMapper = new DefaultLineMapper<AlipayTranDo>();
        lineMapper.setLineTokenizer(tokenizer);
        lineMapper.setFieldSetMapper(new AlipayTranDoFileMapper());
        lineMapper.afterPropertiesSet();
        reader.setLineMapper(lineMapper);
        return reader;
    }



}
